package com.ctgu.chatapp.view.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.ctgu.chatapp.databinding.ItemFriendBinding
import com.ctgu.chatapp.showPojo.Contact

class ContactsAdapter(var contacts: List<Contact>, val chatID: Int, val profile: String) :
    RecyclerView.Adapter<ContactsAdapter.ContactsViewHolder>() {

    lateinit var mRecyclerView: RecyclerView

    class ContactsViewHolder(val binding: ItemFriendBinding) :
        RecyclerView.ViewHolder(binding.root)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        run {
            val binding =
                ItemFriendBinding.inflate(LayoutInflater.from(parent.context), parent, false)
            ContactsViewHolder(binding)
        }


    override fun onBindViewHolder(holder: ContactsViewHolder, position: Int) {
        val contact = contacts[position]
        holder.binding.contact = contact
        holder.binding.chatID = chatID
        holder.binding.profile = profile
        if (position == 0 || contacts[position - 1].index != contact.index) {
            holder.binding.tvIndex.visibility = View.VISIBLE
        } else {
            holder.binding.tvIndex.visibility = View.GONE
        }
    }

    override fun getItemCount() = contacts.size

    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) =
        run { mRecyclerView = recyclerView }
}